"""
AI 服务的 Pydantic 模型定义
"""

from typing import List, Optional

from pydantic import BaseModel, Field, field_validator


class TextToImageRequest(BaseModel):
    """文生图请求模型"""

    prompt: str = Field(..., description="文本提示词", min_length=1, max_length=1000)
    aspect_ratio: Optional[str] = Field(
        default="1:1",
        description="图片宽高比 (1:1, 16:9, 9:16, 4:3, 3:4)",
    )
    response_format: Optional[str] = Field(
        default="url",
        description="响应格式 (url 或 base64)",
    )

    @field_validator("aspect_ratio")
    @classmethod
    def validate_aspect_ratio(cls, v: Optional[str]) -> Optional[str]:
        """验证宽高比参数"""
        if v is None:
            return "1:1"

        valid_ratios = ["1:1", "16:9", "9:16", "4:3", "3:4"]
        if v not in valid_ratios:
            raise ValueError(f"宽高比必须是以下之一: {', '.join(valid_ratios)}")
        return v

    @field_validator("response_format")
    @classmethod
    def validate_response_format(cls, v: Optional[str]) -> Optional[str]:
        """验证响应格式"""
        if v is None:
            return "url"

        valid_formats = ["url", "base64"]
        if v not in valid_formats:
            raise ValueError(f"响应格式必须是以下之一: {', '.join(valid_formats)}")
        return v

    model_config = {
        "json_schema_extra": {
            "examples": [
                {
                    "prompt": "一只可爱的小猫在花园里玩耍，阳光明媚",
                    "aspect_ratio": "16:9",
                    "response_format": "url",
                }
            ]
        }
    }


class ImageInfo(BaseModel):
    """图片信息"""

    url: str = Field(..., description="图片URL")
    index: int = Field(..., description="图片索引")


class TextToImageResponse(BaseModel):
    """文生图响应模型"""

    success: bool = Field(..., description="是否成功")
    message: Optional[str] = Field(default=None, description="响应消息")
    provider: str = Field(..., description="AI提供商")
    model: str = Field(..., description="使用的模型")
    images: List[ImageInfo] = Field(..., description="生成的图片列表")
    revised_prompt: Optional[str] = Field(default=None, description="修正后的提示词")
    usage: dict = Field(..., description="使用量信息")
    cost: Optional[float] = Field(default=None, description="成本（美元）")
    metadata: Optional[dict] = Field(default=None, description="元数据")

    model_config = {
        "json_schema_extra": {
            "examples": [
                {
                    "success": True,
                    "message": "图片生成成功",
                    "provider": "minimax",
                    "model": "text-to-image-01",
                    "images": [
                        {
                            "url": "https://example.com/image1.jpg",
                            "index": 0,
                        }
                    ],
                    "revised_prompt": None,
                    "usage": {"images_generated": 1, "prompt_length": 45},
                    "cost": 0.05,
                    "metadata": {
                        "width": 1024,
                        "height": 1024,
                        "style": "oil-painting",
                    },
                }
            ]
        }
    }


class ErrorResponse(BaseModel):
    """错误响应模型"""

    success: bool = Field(default=False, description="是否成功")
    error: str = Field(..., description="错误信息")
    error_code: Optional[str] = Field(default=None, description="错误代码")
    details: Optional[dict] = Field(default=None, description="详细信息")

    model_config = {
        "json_schema_extra": {
            "examples": [
                {
                    "success": False,
                    "error": "API密钥未配置",
                    "error_code": "CONFIG_ERROR",
                    "details": {"field": "MINIMAX_API_KEY"},
                }
            ]
        }
    }


class HealthResponse(BaseModel):
    """健康检查响应"""

    status: str = Field(..., description="服务状态")
    version: str = Field(..., description="API版本")
    providers: List[str] = Field(..., description="可用的AI提供商")
    features: List[str] = Field(..., description="支持的功能")

